package protocol

import (
	"encoding/binary"
	"encoding/json"
	"gitee.com/tjccc/gomq/lib/logger"
)

// | length | header-len | header | body |

/*
{
	"code" : int,
	"version": int,
	"language": string,
}
*/

type Code uint32

const (
	SEND    Code = 1
	PULL    Code = 2
	ERR     Code = 3
	PullAck Code = 4
)

func MakeMessage(topic string, data []byte) *CustomMsg {
	extMap := map[string]any{}
	extMap["topic"] = topic
	return &CustomMsg{
		Code:   SEND,
		ExtMap: extMap,
		Data:   data,
	}
}

type CustomMsg struct {
	Code     Code           `json:"code"`
	Version  uint32         `json:"version"`
	Language string         `json:"language"`
	ExtMap   map[string]any `json:"extMap"`
	Data     []byte
}

func (msg *CustomMsg) ToBytes() []byte {

	headerBytes, err := json.Marshal(msg)
	if err != nil {
		logger.Error("encode header json fail")
		return nil
	}
	headerLen := len(headerBytes)
	totalLen := headerLen + len(msg.Data)
	totalLenBytes := make([]byte, 4, 4)
	headerLenBytes := make([]byte, 4, 4)
	binary.BigEndian.PutUint32(totalLenBytes, uint32(totalLen))
	binary.BigEndian.PutUint32(headerLenBytes, uint32(headerLen))
	bytes := make([]byte, 0, totalLen)
	bytes = append(bytes, totalLenBytes...)
	bytes = append(bytes, headerLenBytes...)
	bytes = append(bytes, headerBytes...)
	bytes = append(bytes, msg.Data...)
	return bytes
}
